import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

const search = () => import('@/views/search/index.vue')
const searchlist = () => import('@/views/search/list.vue')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'layout',
    component: () => import('@/views/layout'),
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/layout/home')
      },
      {
        path: '/cart',
        name: 'cart',
        component: () => import('@/views/layout/cart')
      },
      {
        path: '/category',
        name: 'category',
        component: () => import('@/views/layout/category')
      },
      {
        path: '/user',
        name: 'user',
        component: () => import('@/views/layout/user')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login')
  },
  {
    path: '/myorder',
    name: 'myorder',
    component: () => import('@/views/myorder')
  },
  {
    path: '/orderdetails',
    name: 'orderdetails',
    component: () => import('@/views/myorder/orderDetails.vue')
  },
  {
    path: '/pay',
    name: 'pay',
    component: () => import('@/views/pay')
  },
  {
    path: '/prodetail/:id?',
    name: 'prodetail',
    component: () => import('@/views/prodetail')
  },
  {
    path: '/search',
    name: 'search',
    component: search
  },
  {
    path: '/searchlist',
    name: 'searchlist',
    component: searchlist
  },
  {
    path: '/addressList',
    name: 'addressList',
    component: () => import('@/views/address/addressList.vue')
  },
  {
    path: '/addressEdit',
    name: 'addressEdit',
    component: () => import('@/views/address/addressEdit.vue')
  }
]

const router = new VueRouter({
  routes
})

// 全局前置守卫通过 router.beforeEach 定义，在每次路由跳转前触发。
// 它接收三个参数：to（目标路由）、from（来源路由）和 next（控制跳转的函数）。
const authUrls = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
  // 看to.path是否在authUrls中出现过
  if (!authUrls.includes(to.path)) {
    // 非授权页面直接放行
    next()
    return // 不加return会报错
  }
  // 授权页面需要验证token，如果token存在，则放行，否则直接跳转到登录页面
  const token = store.getters.token
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
